//
//  BaseCollectionView.swift
//  Advance
//
//  Created by 松松 on 2018/6/29.
//  Copyright © 2018年 整物搭链. All rights reserved.
//

import UIKit
@_exported import MJRefresh

var firstPageNum = 0

public protocol BaseCollectionViewDelegate : NSObjectProtocol {
    func getDate (tableView:BaseCollectionView,pageNum:Int,pageSize:Int)
}

open class BaseCollectionView: UICollectionView {


    public typealias BaseCollectionViewGetDataBlcok = (_ pageNum:Int,_ pageSize:Int)->Void
    public var pageNum : Int = firstPageNum
    public var pageSize : Int = 10
    public weak var baseCollectionViewDelegate : BaseCollectionViewDelegate?
    public var getDataBlock : BaseCollectionViewGetDataBlcok?

    override public init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        super.init(frame: frame, collectionViewLayout: layout)
        setup()
    }

    required public init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        setup()
    }

    public init(frame:CGRect, layout: UICollectionViewLayout,refreshBlock:@escaping BaseCollectionViewGetDataBlcok) {
        super.init(frame: frame, collectionViewLayout: layout)
        setup()
        self.getDataBlock = refreshBlock
    }

    fileprivate func setup(){

        let header = MJRefreshNormalHeader(refreshingBlock: { [weak self] in
            self?.pageNum = firstPageNum
            self?.mj_footer.isHidden = false
            DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 10, execute: {
                self?.mj_header.endRefreshing()
            })
            self?.getDataBlock?(self!.pageSize,self!.pageNum)
            self?.getData()
        })
        self.mj_header = header

        let footer = MJRefreshAutoFooter(refreshingBlock: { [weak self] in
            DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 10, execute: {
                self?.mj_footer.endRefreshing()
            })
            self?.getDataBlock?(self!.pageSize,self!.pageNum)
            self?.getData()
        })
        footer?.isAutomaticallyRefresh = false
        self.mj_footer = footer

    }


    public func pushSuccess(count:Int){
        self.mj_header.endRefreshing()
        self.mj_footer.endRefreshing()
        if count < pageSize{
        self.mj_footer.isHidden = true
        }
        self.pageNum += 1
        self.reloadData()
    }

    fileprivate func getData(){
        self.baseCollectionViewDelegate?.getDate(tableView: self, pageNum: self.pageNum, pageSize: self.pageSize)
    }

}

